package rinpu.springtest.controller;

import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import rinpu.springtest.config.constants.Constants;
import rinpu.springtest.pojo.dto.LoginDto;
import rinpu.springtest.pojo.dto.RegisterDto;
import rinpu.springtest.pojo.entity.SecurityUser;
import rinpu.springtest.service.impl.RegisterServiceImpl;
import rinpu.springtest.service.web.TokenService;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author Rin_pu
 * @Date 2025/9/16 20:29
 * @Description LoginController
 * @TODO
 */
@RequestMapping("/login")
@RestController
public class LoginController {

    @Resource
    private TokenService tokenService;
    @Resource
    private RegisterServiceImpl registerService;
    @Resource
    private AuthenticationManager authenticationManager;

    @PostMapping("/security")
    public String securityLogin(@Valid LoginDto loginDto) {
        // 将用户名和密码托管给Spring Security管理
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginDto.getUsername(), loginDto.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if (authenticate == null) {
            throw new RuntimeException("登录异常");
        }
        SecurityUser user = (SecurityUser) authenticate.getPrincipal();
        // todo Axios包装JSON
        return tokenService.createToken(user);
    }

    @PostMapping("/register")
    public String register(@Valid @RequestBody RegisterDto registerDto) {
        return String.valueOf(registerService.register(registerDto));
    }
}
